import JsonP from 'jsonp';
import axios from 'axios';
import {Modal} from "antd";
import Utils from './../utils/utils';


export default class Axios {
    /**
     * 公共请求封装
     * @author  姚格格
     * @date    2020-03-28 15:27
     */
   static requestList(url, params,_this) {
        let data = {
            params: params
        };

        this.ajax({
            url,
            data
        }).then((data) => {
            if (data && data.result)  {

                let list = data.result.item_list.map((item, index) => {
                    item.key = index;
                    return item
                });

                _this.setState({
                    list,
                    pagination: Utils.pagination(data, (current) => {
                        _this.params.page = current;
                        _this.requestList();
                    })

                })
            }
        })

    }


    static jsonp(options) {

        return new Promise((reslove, rej) => {
            JsonP(options.url, {
                param: 'callback',

            }, function (err, response) {
                //
                if (response.status === 'success') {
                    reslove(response)
                } else {
                    rej(response.message)
                }

            })
        })
    }


    static ajax(options) {
        let loading;
        //isShowLoading 默认是true
        if (options.data && options.data.isShowLoading !==false) {
            loading = document.getElementById('ajaxLoading');
            loading.style.display = 'block';

        }


        let baseApi = 'http://106.12.220.186:4000/api';
        return new Promise((resolve, reject) => {
            axios({
                url: options.url,
                method: 'get',
                baseURL: baseApi,
                timeout: 5000,
                params: (options.data && options.data.params) || ''

            }).then((reponse) => {
                if (options.data && options.data.isShowLoading !==false) {
                    loading = document.getElementById('ajaxLoading');
                    loading.style.display = null;

                }
                if (reponse.status == '200') {
                    let res = reponse.data;
                    if (res.code == '0') {
                        resolve(res)
                    } else {
                        Modal.info({
                            title: '提示',
                            content: 'info'
                        })
                    }
                } else {
                    reject(reponse.data)
                }
            })

        })
    }
}
